import React, { PureComponent, Fragment } from 'react';
import { Spin, Row, Col, Card, Checkbox, Select, Button , message,Radio } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './print.less';
import {abs} from '@/utils/utils';

const { Option } = Select;
const RadioGroup = Radio.Group;
function unitConversion() {
  /**
   * 获取DPI
   * @returns {Array}
   */
  this.conversion_getDPI =function () {
      var arrDPI = new Array;
      if (window.screen.deviceXDPI) {
          arrDPI[0] = window.screen.deviceXDPI;
          arrDPI[1] = window.screen.deviceYDPI;
      } else {
          var tmpNode = document.createElement("DIV");
          tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
          document.body.appendChild(tmpNode);
          arrDPI[0] = parseInt(tmpNode.offsetWidth);
          arrDPI[1] = parseInt(tmpNode.offsetHeight);
          tmpNode.parentNode.removeChild(tmpNode);
      }
      return arrDPI;
  };
  /**
   * px转换为mm
   * @param value
   * @returns {number}
   */
  this.pxConversionMm = function (value) {
      var inch = value/this.conversion_getDPI()[0];
      var c_value = inch * 25.4;
//      console.log(c_value);
      return c_value;
  };
  /**
   * mm转换为px
   * @param value
   * @returns {number}
   */
  this.mmConversionPx = function (value) {
      var inch = value/25.4;
      var c_value = inch*this.conversion_getDPI()[0];
//      console.log(c_value);
      return c_value;
  }
}

@connect(({ deliverManage, loading,global }) => ({
  storeName:global.oemInfo.storeName,
  orderDeliverList:deliverManage.orderDeliverList,
  printItemConfig:deliverManage.printItemConfig,
  loading: loading.effects['deliverManage/GetOrderPrintList'],
  loadingPrintItem: loading.effects['deliverManage/GetPrintItemConfig'],
  oemInfo:global.oemInfo
}))
//@Form.create()
export default class LoanSettleMent extends PureComponent {
  constructor(props) {
    super(props);
    const pageWidth=new unitConversion().mmConversionPx(58);
    this.state = {
      loading: true,
      printItem:[1,2,3,4],
      fontSize:12,
      SkuWidth:58,
      pageWidth:pageWidth
    };
  }

  componentDidMount() {
    window.Isoption = true;
    const {match} = this.props;
    this.requestList(match.params.ids);
    this.getPrintItem(match.params.ids);
    // if(typeof(Storage)!=="undefined"){
    //   this.setState({
    //     printItem:JSON.parse(sessionStorage.getItem('printItem'))||[1,2,3,4],
    //     fontSize:sessionStorage.getItem('fontSize')||12
    //   })

    // }

  }

  componentWillUnmount(){
    window.Isoption = false;
    this.setState = (state, callback) => {
      return
    }
    // if(typeof(Storage)!=="undefined"){
    //   sessionStorage.removeItem('printItem');
    //   sessionStorage.removeItem('fontSize');
    // }
  }

  // 订单列表详情
  requestList= (params) => {
    this.props.dispatch({
      type: 'deliverManage/GetOrderPrintList',
      payload: {
        OrderIds:params
      },
      callback:{
        error:(data)=>{
          if(data.Code !=0){
            router.replace({
              pathname: `/exception/404`,
            });
          }
        }
      }
    })
  }

  // 获取打印选项配置
  getPrintItem = (ids) => {
    this.props.dispatch({
      type: 'localdelivery/GetPrintItemConfig',
      payload: {
        OrderIds:ids
      },
      callBack:{
        success:(data)=>{
          const SkuWidth=data.Data.SkuWidth||58
          const pageWidth=new unitConversion().mmConversionPx(SkuWidth);
          this.setState({
            printItem:data.Data.PrintItem||[1,2,3,4],
            fontSize:data.Data.FontSize||12,
            SkuWidth,
            pageWidth
          })
        },
        error:()=>{

        }
      }
    })
  }


  // 保存打印小票配置
  SaveLPrintConfig = (params) =>{
    const {match} = this.props;
    const {printItem,fontSize,SkuWidth} = this.state;
    this.props.dispatch({
      type: 'localdelivery/SaveLPrintConfig',
      payload: {
        OrderIdList:match.params.ids.split(','),
        PrintItem:printItem,
        FontSize:fontSize,
        SkuWidth
      },
      callBack:{
        success:(data)=>{
          console.log(data)
          message.success('操作成功')

        },
        error:(data) =>{
          console.log(data)
          message.error('操作失败')
        }
      }
    })
  }


  // 打印
  print(){
    this.SaveLPrintConfig();
    window.document.body.innerHTML = window.document.getElementById('billDetails').innerHTML;
    window.print();
    window.location.reload();
  }

  selectPrintItem = (e) => {
    //console.log(e)
    // if(typeof(Storage)!=="undefined"){
    //   sessionStorage.setItem('printItem',JSON.stringify(e))
    // }
    this.setState({
      printItem:e
    });
  }

  ChangeFontSize = (e) => {
    // if(typeof(Storage)!=="undefined"){
    //   sessionStorage.setItem('fontSize',e)
    // }
    this.setState({
      fontSize:e
    });
  }
  onMeasureChange = (e) => {
    const pageWidth=new unitConversion().mmConversionPx(e.target.value);
    this.setState({
      SkuWidth:e.target.value,
      pageWidth
    });
  }

  isShow = (num) => {
    const { printItem } = this.state;
    return printItem.indexOf(num)>-1;
  }



  render() {
    const { orderDeliverList,loadingPrintItem,loading,oemInfo } = this.props;
    const { printItem,fontSize,SkuWidth,pageWidth } = this.state;

    const bdColor="#000";
    return (
      <Fragment>
        <Spin spinning={loading}>
          <div className="xkd-bg-fff">
          <Card bordered={false} className={styles.PrintTitle} >
            <Row>
              <Col span={12} offset={4} style={{textAlign:"left",marginBottom:16}}>
                打印选项：
                <Checkbox.Group onChange={this.selectPrintItem} value={printItem}>
                  <Checkbox value={1}>订单号</Checkbox>
                  <Checkbox value={2}>交易方式</Checkbox>
                  <Checkbox value={3}>交易时间</Checkbox>
                  <Checkbox value={4}>买家留言</Checkbox>
                </Checkbox.Group>
              </Col>
              <Col span={6} style={{textAlign:"left",marginBottom:16}}>
                字号：
                <Select value={fontSize} onChange={this.ChangeFontSize}>
                  <Option value={12}>12px</Option>
                  <Option value={13}>13px</Option>
                  <Option value={14}>14px</Option>
                  <Option value={15}>15px</Option>
                  <Option value={16}>16px</Option>
                </Select>
              </Col>
            </Row>
            <Row type="flex">
              <Col span={12} offset={4} style={{textAlign:"left"}}>
                规格预览：
                <RadioGroup onChange={this.onMeasureChange} value={SkuWidth}>
                  <Radio value={58}>58mm</Radio>
                  <Radio value={75}>75mm</Radio>
                </RadioGroup>
              </Col>
              <Col span={6} style={{textAlign:"left"}}>
                <Button type="primary" onClick={this.print.bind(this)} style={{marginLeft: '42px'}}>立即打印</Button>
              </Col>
            </Row>
          </Card>
          <Row>
            <Col  className={styles.printInfoBox}>
              <div id={'billDetails'} style={{width:`${pageWidth}px`,backgroundColor:"#ccc",margin:"0 auto"}}>
                {orderDeliverList&&orderDeliverList.map((item)=>{
                  let productCount=0;
                  return <div key={item.OrderNo} style={{fontFamily:"黑体",color:`${bdColor}`,padding:"0 8px",fontSize: `12px`}}>
                    <div style={{textAlign:"center",padding:"12px 0",fontSize: 18}}>同城配送#1</div>
                    <div  style={{paddingBottom: 8,textAlign:"center"}}>{oemInfo.storeName}</div>
                    <div style={{padding:"4px 0",borderBottom: `1px dashed ${bdColor}`}}>
                      {this.isShow(1)?<div style={{display: "flex",lineHeight: "22px"}}>
                        <div style={{width:80,textAlign: "left"}}>订单号：</div>
                        <div style={{flex:1,wordBreak: "break-all"}}>{item.OrderNo}</div>
                      </div>:null}
                      {this.isShow(2)?<div style={{display: "flex",lineHeight: "22px"}}>
                        <div style={{width:80,textAlign: "left"}}>交易方式：</div>
                        <div style={{flex:1,wordBreak: "break-all"}}>微信支付</div>
                      </div>:null}
                      {this.isShow(3)?<div style={{display: "flex",lineHeight: "22px"}}>
                        <div style={{width:80,textAlign: "left"}}>交易时间：</div>
                        <div  style={{flex:1,wordBreak: "break-all"}}>{item.CreateTime}</div>
                      </div>:null}
                    </div>
                    <div style={{}}>
                      <div style={{display:"flex",padding:"4px 0",borderBottom: `1px dashed ${bdColor}`,fontSize: `${fontSize}px`}}>
                        <div style={{flex:1}}>商品名称</div>
                        <div style={{width:35,textAlign:"right"}}>数量</div>
                        <div style={{width:50,textAlign:"right"}}>金额</div>
                      </div>
                      {item.OrderItems&&item.OrderItems.map((orderItem,index)=>{
                        productCount+=orderItem.BuyNum;
                        return <div style={{display:"flex",padding:"4px 0",fontSize: `${fontSize}px`}} key={index}>
                          <div style={{flex:1}}>{orderItem.ProductName}</div>
                          <div style={{width:35,textAlign:"right"}}>{orderItem.BuyNum}</div>
                          <div style={{width:50,textAlign:"right"}}>{orderItem.BuyNum*orderItem.SingleFee}</div>
                        </div>
                      })}
                      <div style={{display:"flex",padding:"4px 0"}}>
                        <div style={{flex:1}}>配送费</div>
                        <div style={{width:35,textAlign:"right"}}></div>
                        <div style={{width:50,textAlign:"right"}}>{item.OrderPayFreightAmount}</div>
                      </div>
                    </div>
                    <div style={{padding:"4px 0",borderBottom: `1px dashed ${bdColor}`}}>订单原价：{item.ProductFee}</div>
                    <div style={{padding:"4px 0",borderBottom: `1px dashed ${bdColor}`}}>优惠金额：{item.DiscountFee}</div>
                    <div style={{padding:"4px 0",borderBottom: `1px dashed ${bdColor}`}}>共{productCount}件，实付 {item.OrderPayAmount}元</div>
                    <div>
                      {this.isShow(4)?<div style={{display:"flex",padding:"4px 0"}}>
                        <div style={{width:82}}>买家留言：</div>
                        <div style={{flex:1}}>{item.OrderMsg}</div>
                      </div>:null}
                      <div style={{display:"flex",padding:"4px 0"}}>
                        <div style={{width:70}}>{item.Receiver}</div>
                        <div style={{flex:1}}>{item.ReceiverPhone}</div>
                      </div>
                      <div style={{display:"flex",padding:"4px 0",borderBottom: `1px dashed ${bdColor}`}}>
                        <div style={{width:50}}>地址：</div>
                        <div style={{flex:1}}>{item.FullAddress}</div>
                      </div>
                    </div>
                    <div style={{padding:"4px 0 10px 0",textAlign:"center",fontSize:12}}>
                      谢谢惠顾，欢迎下次光临！
                    </div>
                  </div>
                })}
              </div>
            </Col>
          </Row>
          <Card bordered={false} className={styles.Button}>
            <Row>
              <Col>

              </Col>
            </Row>
          </Card>
          </div>
        </Spin>
      </Fragment>
    );
  }
}
